(function($) {
	var panels = function(els, options) {
		var pbody = $(els), self = this, opts = options, panel = null;
		$.extend(this, {
			init : init,
			getApi : function(e) {
				return panel;
			},
			setOpts : function(options) {
				opts = $.extend( {}, opts, options);
				rSize();
			},
			getOpts : function() {
				return opts;
			}
		});
		function init() {
			panel = pbody.addClass("panel-body").wrap(
					'<div class="panel"></div>').parent();
			panel.css(opts.style);
			panel.addClass(opts.cls);
			pbody.addClass(opts.bodyCls);
			rToolBar();
			// rSize();
		}
		// Setting Toolbar
		function rToolBar() {
			// Setting HeaderToolbar
			if (opts.title) {
				var headerBar = $(
						"<div class=\"panel-header\"><div class=\"panel-title\">"
								+ opts.title + "</div></div>").prependTo(panel);
				var tools = $('<div class="panel-header-tools"></div>')
						.appendTo(headerBar);
				if (opts.htools) {
					for ( var i = opts.htools.length - 1; i >= 0; i--) {
						var tool = $('<div></div>').addClass(
								opts.htools[i].iconCls).appendTo(tools);
						if (opts.htools[i].handler) {
							//tool.bind('click', eval(opts.htools[i].handler));
						}
					}
				}
			}
			// Setting FooterToolbar
			if (opts.footer) {
				var footerBar = $("<div class=\"panel-footer\">&nbsp;ff</div>");
				pbody.addClass("panel-body-footer");
				panel.append(footerBar);
			}
		}
		function rSize() {
			panel.css( {
				width : opts.width,
				height : opts.height,
				left : opts.left,
				top : opts.top
			});
			if (!isNaN(opts.height)) {
				pbody.css( {
					height : opts.height - parseInt(opts.deltaHeight)
				});
			}
			if (!isNaN(opts.width)) {
				pbody.css( {
					width : opts.width - parseInt(opts.deltaWidth)
				});
			}
			pbody.css( {
				margin : 0,
				padding : 0
			});

		}
	};
	$.fn.panel = function(options) {
		var panel = this.eq(typeof options == 'number' ? options : 0).data(
				"panel");
		if (panel) {
			return panel;
		}
		var _opts = $.extend( {}, $.fn.panel.defaults, {
			width : (parseInt($(this).css("width")) || undefined),
			height : (parseInt($(this).css("height")) || undefined),
			top : (parseInt($(this).css("top")) || undefined),
			left : (parseInt($(this).css("left")) || undefined),
			title : $(this).attr("title")
		}, options);
		var opts = $.meta ? $.extend( {}, _opts, this.data()) : _opts;
		this.each(function() {
			panel = new panels(this, opts);
			panel.init();
			$(this).data("panel", panel);
		});
		return opts.api ? panel : this;
	};
	$.fn.panel.defaults = {
		api : true,
		title : null,
		cls : null,
		headerCls : null,
		bodyCls : null,
		style : {},
		width : "auto",
		height : "auto",
		left : null,
		top : null,
		footer : false,
		htools : [],
		ftools : []
	};
})(jQuery);